package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Reference
    MemberService memberService;

    @Autowired
    JedisPool jedisPool;

    /**
     * 步骤：
     *      1. 校验验证码
     *          1.1 获取redis中的验证码
     *          1.2 获取用户输入的验证码
     *          1.3 校验
     *      2. 自动注册为会员
     *      3. 返回登录成功的消息
     *
     * @param map
     * @return
     */
    @RequestMapping("/check")
    public Result check(@RequestBody Map<String, String> map){
        try {
            String telephone = map.get("telephone");

            //1. 校验验证码
            //1.1 获取redis中的验证码
            String validateCodeInRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_LOGIN + "-" + telephone);
            //1.2 获取用户输入的验证码
            String validateCodeInParam = map.get("validateCode");
            //1.3 校验
            //如果校验失败
            if(!(validateCodeInRedis != null && validateCodeInRedis.equals(validateCodeInParam))){
                return new Result(false, MessageConst.VALIDATECODE_ERROR);
            }
            //2. 自动注册为会员
            Member member = memberService.handleMember(map);
            return new Result(true, MessageConst.LOGIN_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }

    }
}
